import request from "../utils/request"
/**
 * 用户登录相关
 */
class userRequest {
    /**
     * 用户登录
     * @param {string} username 
     * @param {string} password 
     * @returns 
     */
    async login(username, password) {
        const responseData = await request({
            url: "/login",
            method: 'post',
            data: {
                username: username,
                password: password
            }
        });

        if (responseData && responseData.token) {
            localStorage.setItem('authToken', responseData.token);
        }
        return responseData;
    }

    /**
     * 用户登出
     */
    async logout() {
        await request({
            url: '/logout',
            method: 'post'
        })

        localStorage.removeItem('authToken');
    }

    /**
     * 
     * @param {userObj} userData 
     * @returns 
     */
    async register(username, password) {
        // POST 请求数据使用 `data`
        const newUser = await request({
            url: '/register',
            method: 'post',
            data: {
                username: username,
                password: password
            }
        });

        return newUser;
    }

    async me() {
        // GET 请求，无需任何参数，token 会被拦截器自动添加
        const userInfo = await request({
            url: '/me',
            method: 'get',
        });

        return userInfo;
    }
}

export default new userRequest();